package com.yc.demo.d0304;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 用户访问控制过滤
 */

@WebFilter(filterName = "LoginFilter",
        value = {"/hello.html","/pub/check.html","/upload.s"})
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println(" LoginFilter 初始化");
    }

    public void destroy() {
        System.out.println(" LoginFilter 销毁");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 判断是否登录 => 在会话中查找loginedUser 属性
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("loginedUser") == null){
            // 说明未登录
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;

            // 获取应用上下文对象
            ServletContext servletContext = request.getServletContext();
            // contextPath => /webdemo_war_exploded
            String contextPath = servletContext.getContextPath();
            // 使用绝对路径访问 登录界面

            // 编码
            String url = contextPath + "/" + URLEncoder.encode("验证码","utf-8") + ".html";
            // 跳转登录页
            httpServletResponse.sendRedirect(url);

            // 保存当前访问的页面地址
            String requestURI = httpServletRequest.getRequestURI();
            System.out.println("requestURI = " + requestURI);
            // 将地址保存到会话
            session.setAttribute("requestURI",requestURI);

            // 返回，不允许访问目标资源，不能执行 chain.doFilter...
            return;
        }
        System.out.println(" LoginFilter 执行过滤（前）");
        chain.doFilter(request, response);
        System.out.println(" LoginFilter 执行过滤（后）");
    }
}
